<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <title>chat</title>
    <link href="../icons/message.png" rel="icon">
    <link rel="stylesheet" type="text/css" href="../css/chat.css">
    <link href="https://unpkg.com/vuesax@4.0.1-alpha.16/dist/vuesax.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>

<body>
<div id="chatRooms">
    <div class="chat">
        <div class="chat-box">
            <div class="chat-sidebar">
                <!--头像-->
                <template>
                    <vs-avatar size="50" badge badge-color="success">
                        <img class="avatar" :src="currentUserInfo.avatar" alt="">
                    </vs-avatar>
                </template>
                <!--用户名-->
                <p class="user-name">{{currentUserInfo.username}}</p>
                <!--图标库-->
                <div class="icons-box" @click="messageListBox=true,friendBox=false"><img src="../icons/message.png"
                                                                                         class="icons"></div>

                <br>
                <div class="icons-box"><img src="../icons/group-chats.png" class="icons"></div>

                <br>
                <div class="icons-box" @click="friendBox=true,addFriendBox=false,messageListBox=false,messageBox=false">
                    <img
                            src="../icons/friend.png" class="icons"></div>

                <br>
                <div class="icons-box" @click="addFriendBox=true,friendBox=true,messageListBox=false,messageBox=false">
                    <img src="../icons/add-friend.png" class="icons"></div>

                <br>
                <div class="icons-box"><img src="../icons/circle-friends.png" class="icons"></div>

                <br>
                <div class="icons-box"><img src="../icons/settings.png" class="icons"></div>

                <br>
                <div class="icons-box"><img src="../icons/exit.png" class="icons"></div>
            </div>

            <!--消息列表-->
            <div class="message-list-box" v-show="messageListBox">
                <button class="icons-bottom" @click="messageListBox=false">
                    <img class="list-copy-icons"
                         src="../icons/turn-left.png">
                </button>
                <input class="select-message" type="text" placeholder="查询消息">
                <table class="messages-list">
                    <tr class="message-line" @click="getMessageHistoryList">
                        <td class="message-line-img-td">
                            <img class="message-line-img" src="../imgs/R-C.jpg">
                        </td>
                        <td class="message-line-td">
                            <span class="message-line-username">Emily Webb</span>
                            <span class="message-line-date">10:20 AM</span>
                            <p class="list-message">Not much haha,what are you...</p>
                        </td>
                    </tr>
                </table>
            </div>

            <!--好友列表-->
            <div class="friend-box" v-show="friendBox">
                <button class="icons-bottom" @click="friendBox=false">
                    <img class="list-copy-icons"
                         src="../icons/turn-left.png">
                </button>
                <input class="select-friend" type="text" placeholder="查询好友">
                <button class="new-friend" @click="getVerificationList"><img class="new-friend-icons"
                                                                             src="../icons/new-friend.png">
                    <span class="new-friend-text">新的朋友</span>
                    <span class="new-friend-notice" v-if="newFriendNotice()">{{newFriendIndex}}</span>
                </button>
                <table class="friend-list">
                    <tr class="friend-line" v-for="friendInfo in friendInfoList">
                        <td>
                            <img class="friend-line-img" :src="friendInfo.avatar">
                        </td>
                        <td class="friend-line-td">
                            <span class="friend-line-username">{{friendInfo.username}}</span>
                        </td>
                        <td class="friend-line-td">
                            <!--好友详细信息列表-->
                            <el-popover
                                    v-model="friendInfoBox"
                                    placement="right"
                                    width="300"
                                    trigger="click">
                                <div class="friend-info">
                                    <img class="friend-avatar" :src="toUserInfo.avatar" alt="">
                                    <p class="friend-username">用户名:{{toUserInfo.username}}</p>
                                    <p class="friend-signature">个性签名：what are you Emily Webb</p>
                                    <button class="friend-icons-one"
                                            @click="messageBox=true,friendInfoBox=false,addFriendBox=false"><img
                                            class="friend-icons-img" src="../icons/send_friend.png"
                                            @click="getMessageHistoryList"></button>
                                    <button class="friend-icons-two" @click="deleteFriend"><img
                                            class="friend-icons-img-delete" src="../icons/delete_friend.png"></button>
                                </div>
                                <el-button slot="reference"
                                           style="border:0px red solid;padding:10px 0px;background:transparent;width: 140px;height:50px;position: absolute; left:0px;top: 0px"
                                           @click="getToUserInfo(friendInfo)">
                                </el-button>
                            </el-popover>
                        </td>
                    </tr>
                </table>
            </div>

            <!--新好友验证对话框-->
            <el-dialog title="新的朋友" :visible.sync="newFriendBox" width="450px">
                <table class="new-friend-box">
                    <tr class="new-friend-line" v-for="newFriendInfo in newFriendList">
                        <td>
                            <img class="add-friend-line-img" src="../imgs/xk.jpg">
                        </td>
                        <td class="new-friend-line-td">
                            <span class="new-friend-line-username"
                                  v-if="newFriendInfo.username == currentUserInfo.username">{{newFriendInfo.friendUsername}}</span>
                            <span class="new-friend-line-username" v-else>{{newFriendInfo.username}}</span>
                        </td>
                        <td class="add-button">
                            <el-button type="primary">同意</el-button>
                            <el-button type="danger">拒绝</el-button>
                        </td>
                    </tr>
                </table>
            </el-dialog>

            <!--添加好友-->
            <div class="add-friend" v-show="addFriendBox">
                <input class="add-select-friend" type="text" placeholder="请输入用户名查找" v-model="addFriendUsername"
                       @keyup.enter="getFriendByUsername">
                <button class="add-select-friend-button" @click="getFriendByUsername">搜索</button>
                <button class="add-icons-bottom" @click="addFriendBox=false">
                    <img class="list-copy-icons"
                         src="../icons/turn-left.png">
                </button>
                <table class="add-friend-list" v-show="addFriendTable">
                    <tr class="add-friend-line">
                        <td>
                            <img class="add-friend-line-img" :src="addFriendInfo.avatar">
                        </td>
                        <td class="add-friend-line-td">
                            <span class="add-friend-line-username">{{addFriendInfo.username}}</span>
                        </td>
                        <td class="add-button">
                            <el-button type="primary" @click="addFriendCheckBox=true" v-show="isNewFriend">添加好友
                            </el-button>
                            <span v-if="isNewFriend == false">已添加</span>
                        </td>
                    </tr>
                </table>
            </div>

            <!--验证消息对话框-->
            <el-dialog title="验证消息" :visible.sync="addFriendCheckBox" width="300px">
                <el-input
                        type="textarea"
                        :rows="2"
                        placeholder="请输入验证消息"
                        v-model="sendVerificationInfo.verificationText">
                </el-input>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="sendVerification">申 请</el-button>
                </div>
            </el-dialog>


            <!--聊天主窗口-->
            <div class="message-window" v-show="messageBox">
                <div class="message-window-head">
                    <button class="copy-icons-bottom" @click="messageBox=false"><img class="copy-icons"
                                                                                     src="../icons/copy.png"></button>
                    <img class="message-line-img" :src="toUserInfo.avatar">
                    <span class="message-window-username">{{toUserInfo.username}}</span>
                    <p class="signature">what are you Emily Webb</p>
                    <img class="message-window-icons" src="../icons/message-icons.png">
                    <img class="message-window-icons" src="../icons/video.png" height="24">
                </div>
                <!--消息窗口-->
                <div class="message-window-main" id="message-window-main">
                    <div class="message-window-main-p">
                        <table class="message-window-main-form" id="message-window-main-form">
                            <tr v-for="(messageText,i) in messageHistoryList">
                                <td class="message-line-img-td">
                                    <span class="message-window-date">{{messageText.sendTime}}</span>
                                    <img :class="messageText.imgClass" :src="messageText.belongAvatar">
                                    <div :class="messageText.msgClass">
                                    <span class="message">
                                        {{messageText.message}}
                                    </span>
                                    </div>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>

                <div class="message-window-bottom">
                    <textarea class="message-window-bottom-text" id="textarea" placeholder="Message(Max length:130)"
                              v-model="messageInfo.message" @keyup.enter="sendClick" maxlength="130">
                    </textarea>
                    <button class="message-window-bottom-button" @click="sendClick"><img
                            class="message-window-bottom-icons"
                            src="../icons/send.png"></button>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="../js/vue.js"></script>
<script src="../js/axios-0.18.0.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script src="https://unpkg.com/vuesax@4.0.1-alpha.16/dist/vuesax.min.js"></script>

<!--
1，点击发送
2.建立websocket连接
3，发送数据服务端
-->

<script>
    new Vue({
        el: '#chatRooms',
        data: {
            //dev-url
            devUrl: "localhost",
            //pro-url
            proUrl: "https://tg05.icu",
            //websocket对象
            websocket: {},
            //消息窗口开关
            messageBox: false,
            //消息列表窗口
            messageListBox: false,
            //好友列表窗口
            friendBox: true,
            //添加好友窗口
            addFriendBox: true,
            //好友列表
            friendInfoList: [],
            //添加好友
            addFriendInfo: {},
            //查找好友表格
            addFriendTable: false,
            //添加好友对话框
            addFriendCheckBox: false,
            //发送验证对象
            sendVerificationInfo: {
                verificationText: ""
            },
            //查询用户是否为好友
            isNewFriend: true,
            //新好友集合
            newFriendBox: false,
            //新好友通知角标
            newFriendIndex: 0,
            //addFriendUsername
            addFriendUsername: "",
            //新好友验证集合
            newFriendList: [],
            //好友信息盒子
            friendInfoBox: false,
            //选中对象信息
            toUserInfo: {},
            //消息对象
            messageInfo: {},
            //消息历史记录
            messageHistoryList: [],
            //当前登录对象信息
            currentUserInfo: {},
            //axios对象
            axios: ""
        },
        //钩子函数，VUE对象初始化完成后自动执行
        created() {
            this.currentUserInfo.username = location.search.substring(1);
            this.currentUserInfo.token = localStorage.getItem(this.currentUserInfo.username);
            //设置统一响应标头
            this.axios = axios.create({
                timeout: 10000, // 请求超时时间
                headers: {"Authorization": this.currentUserInfo.token}
            });
            this.getCurrentUserInfo();
            setTimeout(() => {
                this.getFriendInfoList();
                this.initWebSocket();
            }, 300);
        },
        beforeDestroy() {
            this.websocket.onclose = this.websocketOnClose();
            localStorage.removeItem(this.currentUserInfo.username);
        },
        methods: {
            //websocket
            initWebSocket() {
                this.websocket = new WebSocket("ws://localhost/websocket/" + this.currentUserInfo.username)
                this.websocket.onopen = this.websocketOnOpen;
                this.websocket.onerror = this.websocketOnError;
                this.websocket.onmessage = this.websocketOnMessage;
            },
            //onOpen
            websocketOnOpen() {
                console.log(this.currentUserInfo.username + "连接成功!")
            },
            //onMessage
            websocketOnMessage(resp) {
                const message = JSON.parse(resp.data);
                if (resp.data != null) {
                    this.messageHistoryList.push(message);
                }
                this.isCurrent();
                this.trRows();
            },
            //onClose
            websocketOnClose() {
                console.log(this.currentUserInfo.user + "连接断开!")
                this.initWebSocket();
            },
            //OnError
            websocketOnError(e) {
                console.log(e + "连接出错!")
            },
            //点击发送事件
            sendClick() {
                if (this.messageInfo.message != null && this.messageInfo.message.trim().length > 0) {
                    this.messageInfo.sendTime = new Date().toLocaleString();
                    this.messageInfo.fromUsername = this.currentUserInfo.username;
                    this.messageInfo.toUsername = this.toUserInfo.username;
                    this.websocket.send(JSON.stringify(this.messageInfo));
                    this.saveMessage();
                } else {
                    this.$message.error("消息不能为空!!");
                    this.messageInfo.message = "";
                }
            },
            //获取当前登录用户信息,并设置统一请求头
            getCurrentUserInfo() {
                this.axios.get("http://" + this.devUrl + "/users").then(rsp => {
                    if (rsp.data.code == 20041) {
                        this.currentUserInfo = rsp.data.data;
                        console.log(this.currentUserInfo)
                    } else {
                        this.isLogin()
                    }
                })
            },
            //获取消息历史记录
            getMessageHistoryList() {
                this.axios.get("http://" + this.devUrl + "/chats/" + this.currentUserInfo.username + "/" + this.toUserInfo.username).then(rsp => {
                    if (rsp.data.code == 20041) {
                        this.messageHistoryList = rsp.data.data;
                        this.isCurrent();
                        this.trRows();
                        this.messageBox = true;
                        // console.log("history");
                    } else if (rsp.data.code == 20040) {
                        console.log("history404")
                    } else {
                        console.log("繁忙!!!")
                    }
                })
            },
            //存储消息方法
            saveMessage() {
                this.axios.post("http://" + this.devUrl + "/chats", this.messageInfo).then(rsp => {
                    if (rsp.data.code == 20011) {
                        console.log("消息保存成功!")
                        this.messageInfo.message = "";
                        this.getMessageHistoryList();
                    } else if (rsp.data.code == 20010) {
                        console.log("消息保存失败!")
                    } else {
                        console.log("服务异常！")
                    }
                })
            },
            //查询当前用户好友信息
            getFriendInfoList() {
                this.axios.get("http://" + this.devUrl + "/friends/" + this.currentUserInfo.username).then(rsp => {
                    if (rsp.data.code == 20041) {
                        this.friendInfoList = rsp.data.data;
                    } else {
                        console.log("查询好友错误！")
                    }
                })
            },
            //删除好友
            deleteFriend() {
                this.$confirm('此操作将永久删除该好友, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    center: true
                }).then(() => {
                    this.axios.delete("http://" + this.devUrl + "/friends/" + this.currentUserInfo.username + "/" + this.toUserInfo.username).then(rsp => {
                        if (rsp.data.code == 20021) {
                            this.getFriendInfoList();
                            this.$message.success(rsp.data.message);
                        } else if (rsp.data.code == 20020) {
                            this.$message.error(rsp.data.message);
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //选中用户对象
            getToUserInfo(friendInfo) {
                console.log(friendInfo)
                this.toUserInfo = friendInfo;
            },
            //判断当前用户
            isCurrent() {
                for (let i = 0; i < this.messageHistoryList.length; i++) {
                    if (this.currentUserInfo.username === this.messageHistoryList[i].fromUsername) {
                        this.messageHistoryList[i].imgClass = "message-window-img-right";
                        this.messageHistoryList[i].msgClass = "bubble-right";
                        this.messageHistoryList[i].belongAvatar = this.currentUserInfo.avatar;
                    } else {
                        this.messageHistoryList[i].imgClass = "message-window-img-left";
                        this.messageHistoryList[i].msgClass = "bubble-left";
                        this.messageHistoryList[i].belongAvatar = this.toUserInfo.avatar;
                    }
                }
            },
            //控制消息窗口滚轮底部方法
            trRows() {
                if (this.messageHistoryList.length >= 4) {
                    document.getElementById("message-window-main").style.flexDirection = "column-reverse";
                }
            },
            //判断当前是否登录
            isLogin() {
                if (this.currentUserInfo.age) {
                    alert("用户未登录或账户失效，请重新登录!");
                    location.href = '/pages/login.html';
                }
            },
            //新好友通知角标
            newFriendNotice() {
                if (this.newFriendIndex == 0) {
                    return false;
                }
                return true;
            },
            //添加好友根据用户名查询
            getFriendByUsername() {
                this.isFriend();
                if (this.addFriendUsername == this.currentUserInfo.username) {
                    this.$message.info("不可查询当前登录用户!!!")
                } else if (this.addFriendUsername == null || typeof this.addFriendUsername == "undefined" || this.addFriendUsername == "") {
                    this.$message.info("查询用户名不能为空!")
                } else {
                    axios.get("http://" + this.devUrl + "/users/add/" + this.addFriendUsername).then(rsp => {
                        if (rsp.data.code == 20041) {
                            this.addFriendTable = true;
                            this.addFriendInfo = rsp.data.data;
                            this.initVerificationInfo();
                            this.$message.success(rsp.data.message)
                        } else if (rsp.data.code == 20040) {
                            this.addFriendTable = false;
                            this.$message.info(rsp.data.message)
                        } else {
                            this.addFriendTable = false;
                            this.$message.error(rsp.data.message)
                        }
                    })
                }
            },
            //查询当前用户是否为好友
            isFriend() {
                for (const newFriend in this.friendInfoList) {
                    if (this.friendInfoList[newFriend].username == this.addFriendUsername) {
                        this.isNewFriend = false;
                    } else {
                        this.isNewFriend = true;
                    }
                }
            },
            //初始化发送验证对象
            initVerificationInfo() {
                let sendVerificationInfo = this.sendVerificationInfo;
                sendVerificationInfo.username = this.currentUserInfo.username;
                sendVerificationInfo.friendUsername = this.addFriendInfo.username;
                sendVerificationInfo.askForTime = new Date().toLocaleString();
            },
            //点击申请发送验证方法
            sendVerification() {
                if (this.sendVerificationInfo.verificationText.trim() == "" || this.sendVerificationInfo.verificationText == null) {
                    this.$message.info("验证消息不能为空");
                } else {
                    this.axios.post("http://" + this.devUrl + "/friends", this.sendVerificationInfo).then(rsp => {
                        if (rsp.data.code == 20011) {
                            this.$message.success(rsp.data.message);
                        } else if (rsp.data.code == 20010) {
                            this.$message.info(rsp.data.message);
                        } else {
                            this.$message.error(rsp.data.message);
                        }
                        this.addFriendCheckBox = false;
                    })
                }
            },
            //获取验证信息
            getVerificationList() {
                this.newFriendBox = true
                this.axios.get("http://" + this.devUrl + "/friends/verification/" + this.currentUserInfo.username).then(rsp => {
                    if (rsp.data.code == 20041) {
                        this.newFriendList = rsp.data.data;
                    } else if (rsp.data.code == 20040) {
                        this.$message.info(rsp.data.message);
                    } else {
                        this.$message.error(rsp.data.message);
                    }
                })
            },
            //遍历分类（等待验证-通过-拒绝-添加成功）
            isVerificationType() {
                for (const newFriendInfo of this.newFriendList) {
                    if (newFriendInfo.status == 0) {
                        if (this.currentUserInfo.username == newFriendInfo.username) {
                            //等待验证

                        } else if (this.currentUserInfo.username == newFriendInfo.friendUsername) {
                            //通过-拒绝

                        }
                    } else {
                        if (this.currentUserInfo.username == newFriendInfo.friendUsername) {
                            //已通过

                        } else if (this.currentUserInfo.username == newFriendInfo.username) {
                            //已添加

                        }
                    }
                }
            }
        }
    });

    //textarea回车不换行
    document.getElementById('textarea').addEventListener('keydown', e => {
        if (e.keyCode === 13) {
            e.preventDefault()
        }
    });

</script>
</body>

</html>